package com.crane.oss.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crane.oss.sys.dao.MenuApiDao;
import com.crane.oss.sys.model.MenuApi;
import com.crane.oss.sys.service.MenuApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

@Service("menuApiService")
public class MenuApiServiceImpl extends ServiceImpl<MenuApiDao,MenuApi> implements MenuApiService {

    private static final Logger logger = LoggerFactory.getLogger(MenuApiServiceImpl.class);

    @Resource
    protected MenuApiDao menuApiDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(Long menuId, List<Long> apiIdList) {
        logger.info("MenuApiService saveBatch menuId={},apiIdList={}", menuId, apiIdList);
        if (CollectionUtils.isEmpty(apiIdList)) {
            return;
        }

        // 去重
        Set<Long> apiIdSet = new HashSet<>(apiIdList);
        List<Long> list = new ArrayList<>();
        list.addAll(apiIdSet);

        // 保存角色与菜单关系
        List<MenuApi> menuApiList = new ArrayList<>();
        for (Long apiId : list) {
            MenuApi menuApi = new MenuApi();
            menuApi.setApiId(apiId);
            menuApi.setMenuId(menuId);
            menuApi.setCreateTime(new Date());
            menuApiList.add(menuApi);
        }
        this.saveBatch(menuApiList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(Long menuId, List<Long> oldApiIdList, List<Long> newApiIdList) {
        logger.info("MenuApiService updateBatch menuId={}, oldApiIdList={}, apiIdList={}", menuId, oldApiIdList, newApiIdList);
        if (!CollectionUtils.isEmpty(oldApiIdList)) {
            this.deleteByMenuId(menuId);
            if (!CollectionUtils.isEmpty(newApiIdList)) {
                this.saveBatch(menuId, newApiIdList);
                return;
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByApiId(Long apiId) {
        logger.info("MenuApiService deleteByApiId apiId={}", apiId);
        return menuApiDao.delete(new LambdaQueryWrapper<MenuApi>().eq(MenuApi::getApiId,apiId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByMenuId(Long menuId) {
        logger.info("MenuApiService deleteByMenuId menuId={}", menuId);
        return menuApiDao.delete(Wrappers.lambdaQuery(MenuApi.class).eq(MenuApi ::getMenuId,menuId));
    }

}
